<template>
    <el-dialog
        v-model="roleSetMenuVisible"
        title="分配菜单"
        @open="handleDialogOpen"
        @close="handleClose"
        draggable
    >
        <el-transfer
            v-model="selectedMenuIds"
            :data="data"
            :titles="['可选菜单', '已选菜单']"
            filter-placeholder="请输入菜单名称"
            filterable
        />
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="handleClose">取消</el-button>
                <el-button type="primary" @click="submitForm">确认</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, inject } from 'vue'
import { getRoleMenuIdList, roleSetMenu } from '@/api/system/role'
import { getMenuList } from '@/api/system/menu'
import { useRoute, useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'

const { t } = useI18n()

const route = useRoute()
const router = useRouter()

const data = ref([]) // 存储菜单列表的数据
const selectedMenuIds = ref([]) // 存储选中的菜单ID

const { roleSetMenuVisible, selectedRowId } = inject('roleSetMenu')
function handleDialogOpen() {
    if (selectedRowId.value) {
        roleSetMenuForm.roleId = selectedRowId.value
        _getMenuList()
        getRoleMenuIdList(roleSetMenuForm.roleId).then((response) => {
            if (response && response.data) {
                selectedMenuIds.value = response.data
            }
        })
    }
}

const roleSetMenuForm = reactive({
    roleId: undefined,
    menuIds: []
})
/**
 * 获取菜单列表
 */
function _getMenuList() {
    getMenuList().then((response) => {
        if (response && response.data) {
            data.value = response.data.map((item) => {
                return {
                    key: item.id,
                    label: t(item.name),
                    disabled: item.status === 0 //0 禁用
                }
            })
        }
    })
}
/**
 * 提交表单
 */
function submitForm() {
    roleSetMenuVisible.value = false
    // 更新表单中的菜单ID数组
    roleSetMenuForm.menuIds = selectedMenuIds.value
    roleSetMenu(roleSetMenuForm)
    resetRoleSetMenuForm()
    // 刷新表格
    const { query, path } = route
    router.replace({ path: '/redirect' + path, query: query })
}
// 重置 roleSetMenuForm 的函数
const resetRoleSetMenuForm = () => {
    Object.keys(roleSetMenuForm).forEach((key) => {
        // 如果当前值是数组，则重置为空数组，否则设为 undefined
        roleSetMenuForm[key] = Array.isArray(roleSetMenuForm[key]) ? [] : undefined
    })
    selectedMenuIds.value = []
}
// 处理对话框关闭事件
function handleClose() {
    resetRoleSetMenuForm()
    roleSetMenuVisible.value = false
    selectedMenuIds.value = []
}
</script>
<style lang="scss" scoped></style>
